/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.cabinetgroup.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseClientLoginUser;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpClientLoginUserUtil;
import vip.xiaonuo.auth.core.util.StpClientUtil;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.cabinetdoor.entity.BizCabinetDoor;
import vip.xiaonuo.biz.modular.cabinetgroup.entity.BizCabinetGroup;
import vip.xiaonuo.biz.modular.cabinetgroup.mapper.BizCabinetGroupMapper;
import vip.xiaonuo.biz.modular.cabinetgroup.param.*;
import vip.xiaonuo.biz.modular.cabinetgroup.service.BizCabinetGroupService;
import vip.xiaonuo.biz.modular.cabinetgroup.vo.BizCabinetGroupResp;
import vip.xiaonuo.biz.modular.cabinetgroup.vo.ClientCabinetGroup;
import vip.xiaonuo.biz.modular.cabinetinfo.entity.BizCabinetInfo;
import vip.xiaonuo.biz.modular.cabinetinfo.mapper.BizCabinetInfoMapper;
import vip.xiaonuo.biz.modular.cabinetpermission.service.BizCabinetPermissionUtil;
import vip.xiaonuo.biz.modular.locationarea.entity.BizLocationArea;
import vip.xiaonuo.biz.modular.locationarea.service.BizLocationAreaService;
import vip.xiaonuo.biz.modular.locationbuilding.entity.BizLocationBuilding;
import vip.xiaonuo.biz.modular.locationbuilding.service.BizLocationBuildingService;
import vip.xiaonuo.biz.modular.locationroom.entity.BizLocationRoom;
import vip.xiaonuo.biz.modular.locationroom.service.BizLocationRoomService;
import vip.xiaonuo.biz.modular.relation.entity.BizRelation;
import vip.xiaonuo.biz.modular.relation.enums.BizRelationCategoryEnum;
import vip.xiaonuo.biz.modular.relation.service.BizRelationService;
import vip.xiaonuo.common.exception.CommonException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 组柜管理Service接口实现类
 *
 * @author kongxm
 * @date 2022/11/12 16:05
 **/
@Service
public class BizCabinetGroupServiceImpl extends ServiceImpl<BizCabinetGroupMapper, BizCabinetGroup> implements BizCabinetGroupService {
    @Resource
    private BizRelationService bizRelationService;
    @Resource
    private BizCabinetPermissionUtil bizCabinetPermissionUtil;
    @Resource
    private BizCabinetInfoMapper bizCabinetInfoMapper;

    @PostConstruct
    public void repairPinyin() {
        // for cabinet group
        list(new LambdaQueryWrapper<BizCabinetGroup>().isNull(BizCabinetGroup::getCabinetGroupNamePinyin)).forEach(item -> {
            BizCabinetGroup bizCabinetGroup = new BizCabinetGroup();
            bizCabinetGroup.setId(item.getId());
            bizCabinetGroup.setCabinetGroupNamePinyin(PinyinUtil.getFirstLetter(item.getCabinetGroupName(), ""));
            updateById(bizCabinetGroup);
        });
    }

    @Override
    public Page<BizCabinetGroupResp> page(BizCabinetGroupPageParam bizCabinetGroupPageParam) {
        // Here should judge the auth
        if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) { // 只查询自己的组柜
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            bizCabinetGroupPageParam.setUserId(saBaseLoginUser.getId());
        }
        return getBaseMapper()
                .page(Page.of(bizCabinetGroupPageParam.getCurrent(), bizCabinetGroupPageParam.getSize()),
                        bizCabinetGroupPageParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BizCabinetGroupAddParam param) {
        // 组柜编号：必填，唯一，不可编辑。
        long count = count(new LambdaQueryWrapper<BizCabinetGroup>().eq(BizCabinetGroup::getCabinetGroupCode, param.getCabinetGroupCode()));
        Assert.isTrue(count == 0, "组柜编号{}已存在", param.getCabinetGroupCode());
        BizCabinetGroup bizCabinetGroup = BeanUtil.toBean(param, BizCabinetGroup.class);
        if (StringUtils.isNotEmpty(bizCabinetGroup.getCabinetGroupName())) {
            bizCabinetGroup.setCabinetGroupNamePinyin(PinyinUtil.getFirstLetter(bizCabinetGroup.getCabinetGroupName(), ""));
        }
        long cabinetIdentifyCount = count(new LambdaQueryWrapper<BizCabinetGroup>().eq(BizCabinetGroup::getCabinetIdentify, param.getCabinetIdentify()));
        Assert.isTrue(cabinetIdentifyCount == 0, "设备硬件标识{}已存在", param.getCabinetIdentify());
        this.save(bizCabinetGroup);
        saveRelations(bizCabinetGroup.getId(), param.getAdminUserIds());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(BizCabinetGroupEditParam param) {
        bizCabinetPermissionUtil.hasPermission(param.getId(), null, null);
        // 组柜编号：必填，唯一，不可编辑。
        long count = count(new LambdaQueryWrapper<BizCabinetGroup>()
                .eq(BizCabinetGroup::getCabinetGroupCode, param.getCabinetGroupCode())
                .ne(BizCabinetGroup::getId, param.getId()));
        Assert.isTrue(count == 0, "组柜编号{}已存在", param.getCabinetGroupCode());
        BizCabinetGroup bizCabinetGroup = this.queryEntity(param.getId());
        BeanUtil.copyProperties(param, bizCabinetGroup);
        if (StringUtils.isNotEmpty(bizCabinetGroup.getCabinetGroupName())) {
            bizCabinetGroup.setCabinetGroupNamePinyin(PinyinUtil.getFirstLetter(bizCabinetGroup.getCabinetGroupName(), ""));
        }
        long cabinetIdentifyCount = count(new LambdaQueryWrapper<BizCabinetGroup>()
                .eq(BizCabinetGroup::getCabinetIdentify, param.getCabinetIdentify())
                .ne(BizCabinetGroup::getId, param.getId()));
        Assert.isTrue(cabinetIdentifyCount == 0, "设备硬件标识{}已存在", param.getCabinetIdentify());
        this.updateById(bizCabinetGroup);
        saveRelations(bizCabinetGroup.getId(), param.getAdminUserIds());
        // 修改了设备硬件标识需要更新其下所有的柜子
        bizCabinetInfoMapper.selectList(new LambdaQueryWrapper<BizCabinetInfo>().eq(BizCabinetInfo::getCabinetGroupId, param.getId())).forEach(cabinetInfo -> {
            cabinetInfo.setCabinetIdentify(param.getCabinetIdentify());
            bizCabinetInfoMapper.updateById(cabinetInfo);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizCabinetGroupIdParam> bizCabinetGroupIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(bizCabinetGroupIdParamList, BizCabinetGroupIdParam::getId));
        bizCabinetGroupIdParamList.forEach(item -> {
            bizCabinetPermissionUtil.hasPermission(item.getId(), null, null);
            bizRelationService.remove(new LambdaQueryWrapper<BizRelation>().eq(BizRelation::getObjectId, item.getId()));
        });
    }

    @Override
    public BizCabinetGroup detail(BizCabinetGroupIdParam bizCabinetGroupIdParam) {
        return this.queryEntity(bizCabinetGroupIdParam.getId());
    }

    @Override
    public BizCabinetGroup queryEntity(String id) {
        BizCabinetGroup bizCabinetGroup = this.getById(id);
        if (ObjectUtil.isEmpty(bizCabinetGroup)) {
            throw new CommonException("组柜管理不存在，id值为：{}", id);
        }
        return bizCabinetGroup;
    }

    private void saveRelations(String groupCabinetId, String adminIds) {
        if (StringUtils.isEmpty(groupCabinetId)) return;
        if (StringUtils.isNotEmpty(adminIds)) {
            List<String> list = Arrays.stream(adminIds.split(",")).collect(Collectors.toList());
            bizRelationService.saveRelationBatchWithClear(groupCabinetId, list,
                    BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
        }
    }

    @Override
    public List<ClientCabinetGroup> listCabinetGroupForClientUserPerm(Integer cabinetGroupType) {
        LambdaQueryWrapper<BizCabinetGroup> lambdaQueryWrapper = new LambdaQueryWrapper<BizCabinetGroup>()
                .eq(BizCabinetGroup::getState, 1)
                .eq(BizCabinetGroup::getDeleteFlag, "NOT_DELETE");

        if(cabinetGroupType != null) {
            lambdaQueryWrapper.eq(BizCabinetGroup::getCabinetGroupType, cabinetGroupType);
        }

        return getBaseMapper().selectList(lambdaQueryWrapper)
                .stream().map(item -> {
                    ClientCabinetGroup cabinetGroup = new ClientCabinetGroup();
                    cabinetGroup.setId(item.getId());
                    cabinetGroup.setCabinetGroupName(item.getCabinetGroupName());
                    cabinetGroup.setMaxPermDays(item.getMaxPermDays());
                    cabinetGroup.setCabinetGroupCode(item.getCabinetGroupCode());
                    return cabinetGroup;
                }).collect(Collectors.toList());
    }

    @Override
    public List<ClientCabinetGroup> listCabinetGroupForClientUserEvent() {
        String userId = StpClientUtil.getLoginIdAsString();
        return getBaseMapper().listCabinetGroupForClientUserEvent(userId);
    }

    @Override
    public List<ClientCabinetGroup> listCabinetGroupByGoodsForClient() {
        return getBaseMapper().listCabinetGroupByGoodsForClient();
    }

    @Override
    public List<BizCabinetGroup> listCabinetGroupByAdminId(String userId, Integer cabinetGroupType) {
        return getBaseMapper().listCabinetGroupByAdminId(userId, cabinetGroupType);
    }

    @Override
    public List<BizCabinetGroup> listCabinetGroup(Integer cabinetGroupType) {
        LambdaQueryWrapper<BizCabinetGroup> lambdaQueryWrapper = new LambdaQueryWrapper<BizCabinetGroup>()
                .eq(BizCabinetGroup::getState, 1)
                .eq(BizCabinetGroup::getCabinetGroupType, cabinetGroupType);
        // Here should judge the auth
        if (!StpUtil.hasRoleOr("superAdmin", "sysAdmin")) { // 如果不是管理员，那其他用户的角色，只能看到自己管理的组柜
            SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
            // 这里获得到有管理权限的组柜id
            List<String> cabinetGroupIds = bizRelationService.getRelationObjectIdListByTargetIdAndCategory(saBaseLoginUser.getId(),
                    BizRelationCategoryEnum.BIZ_RELATION_CABINET_GROUP_AND_ADMIN_USER.getValue());
            if (CollectionUtils.isEmpty(cabinetGroupIds)) return Lists.newArrayList(); // 如果没有组柜权限，返回空
            lambdaQueryWrapper.in(BizCabinetGroup::getId, cabinetGroupIds);
        }
        return list(lambdaQueryWrapper);
    }
}
